<?php
session_start();
global $cfg, $fullpath, $path, $mode, $audioext, $config_inet_hash, $dirlist, $fullpathToFile;

/***********************************************\
 *     Playlist add/remove/clear options       *
\***********************************************/
//if it was requested to add a new item to the playlist, let's do so
session_start();
//if a new item was posted back to be added to the playlist, let's add it
if(isset($_POST['addtoqueue'])){
    //if the array doesn't already exist let's create it
    $_SESSION['playlist'][] = $_POST['addtoqueue'];
}
//if the user wants to remove an item from the queue, let's do that then re-arrange it
if(isset($_POST['removefromqueue'])){
    //if the user requested to remove "everything", let's clear the playlist
    if($_POST['removefromqueue'] == "everything"){
        //unset the whole variable
        unset($_SESSION['playlist']);
    }else{
        //otherwise, just remove the item from the array
        unset($_SESSION['playlist'][$_POST['removefromqueue']]);
    }
    //then re-index it so the numbering makes sense
    $_SESSION['playlist'] = array_values($_SESSION['playlist']);
}

/******************************************************\
 *  GENERATE PLAYLIST                                 *
 *  This function will generate an M3U based playlist *
 *  based on either the current directory listing     *
 *  ($dirlist) of the current full path ($fullpath)   *
 *  OR                                                *
 *  the function will generate a playlist based on    *
 *  playlist items in the session variable 'playlist' *
 *                                                    *
\******************************************************/ 
function generatePlaylist(){
    global $fullpath, $path, $mode, $audioext, $config_inet_hash, $dirlist;
    
    //clear out what might have been sent so far
    ob_clean();
    flush();

    //set the headers and send the content of the file
    
    // Pragma, Expiration, Cache-Control
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); 
    
    // if it's stream let's inline - if it's download let's attach
    header("Content-Disposition: attachment; filename=\"playlist.m3u\"; "); //attachment to download, inline to view in browser
    
    //Set the content length and the transfer encoding
    //header("Content-Length: ".filesize($fullpath));
    header('Content-Transfer-Encoding: binary');			
    header('Content-Type: ');
    // We'll be outputting a ___

    //send the content type
    header("Content-Type: audio/mpegurl");	
    
    // The content of the file
    echo "#EXTM3U\n\n";
    
    //setup the web address based on how the request came in (eg. what URL)
    $webaddress = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
    
    if($mode == "playlist"){
        foreach($_SESSION['playlist'] as $file){
            //breakout the fullpath and file
            preg_match('/([^\.]+)\/([^\/]+)$/', $file, $matches);
            $fullpath = $matches[1];
            $item = $matches[2];
            
            //set the line header with the info
            echo "#EXTINF: $item\n";
            echo "http://$webaddress?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=download";
            //if($config_inet_secure == "enable"){
            echo "&inet_hash=$config_inet_hash";
            //}
            echo "\n";
        }
    }else{
        //loop through the files and give a URL only to the MP3s (line by line)
        //let's loop through the directory list
        foreach($dirlist as $item){
            //get the file type
            $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
            //if it's an MP3, let's echo it out
            
            if(in_array($ext,$audioext)){
            //if($ext == "mp3"){
                echo "#EXTINF: $item\n";
                echo "http://$webaddress?path=".urlencode($fullpath)."&file=".urlencode($item)."&action=download";
                //if($config_inet_secure == "enable"){
                echo "&inet_hash=$config_inet_hash";
                //}
                echo "\n";
            }
        }
    }
    exit;
}
/**********************************************************\
 *  STREAM THUMB                                          *
 * This function will stream a thumbnail version of a     *
 * picture based on the $fullpathToFile global variable   *
 *                                                        *
 * It calls the createthumbnail function which will check *
 * to see if the thumbnail already exists and if the      *
 * thumbnail doesn't exists, the createthubmnail func     *
 * will create the thumbnail.                             *
 *                                                        *
\**********************************************************/
function streamThumb(){
    global $file, $path, $fullpathToFile;
    echo "The full path is: ".$fullpathToFile."<br />";
    $thumbnm = createthumbnail($fullpathToFile);
    echo "The thumbnm is: ".$thumbnm."<br />";
    if($thumbnm != false && $thumbnm != "fail"){
        //stream out the file
        //clear out what might have been sent so far
        ob_clean();
        flush();
        
        /* Pragma, Expiration, Cache-Control -- these need to be reviewed for ca
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false); 
        */
        
        //create the etag and check it for caching purposes
        if($thumbnm == "thumbdir"){
            $last_modified_time = filemtime($fullpathToFile);
            $etag = md5($fullpathToFile.$last_modified_time);
        }else{
            $last_modified_time = filemtime($path."/.thumbs/".$thumbnm);
            $etag = md5($path."/.thumbs/".$thumbnm.$last_modified_time);
        }

        header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
        header("Etag: $etag");

        if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
            header("HTTP/1.1 304 Not Modified");
            exit;
        } 
        
        //stream the file
        if($thumbnm == "thumbdir"){
            header("Content-Disposition: inline; filename=".$file); //attachment to download, inline to view in browser
        }else{
            header("Content-Disposition: inline; filename=".$thumbnm); //attachment to download, inline to view in browser
        }
        //Set the content length and the transfer encoding
        //header("Content-Length: ".filesize($fullpathToFile));
        header('Content-Transfer-Encoding: binary');			
        header('Content-Type: ');
        
        // We'll be outputting a ___
        header('Content-Type: image/jpg');
        
        // The content of the file
        if($thumbnm == "thumbdir"){//if the createthumbnail function returned "thumbdir, let's just use the file itself
            readfile($fullpathToFile);
        }else{ //otherwise we'll use the path to the subdirectory which should be the thumbnails
            readfile($path."/.thumbs/".$thumbnm);
        }
        exit;
    }
    else{
        //stream out an error image instead
        echo "Something failed.";
        
    }
}
/**********************************************************\
 *  GENERATE THUMB                                        * 
 * This function is a deprecated piece of code.           *
 * This function will  a thumbnail on the fly and *
 * stream it.                                             *
 *                                                        *
 * Note: there is no caching on this function             *
\**********************************************************/
function generateThumb() { 
      // all this code should get replaced with a few calls to the functions I am creating...
      //echo "We will generate you a thumb";
      ob_clean();
      //flush();
      // Set a maximum height and width
      $width = 100;
      $height = 100;

      // Content type
      header('Content-type: image/jpeg');

      // Get new dimensions
      list($width_orig, $height_orig) = getimagesize($fullpathToFile);

      $ratio_orig = $width_orig/$height_orig;

      if ($width/$height > $ratio_orig) {
         $width = $height*$ratio_orig;
      } else {
         $height = $width/$ratio_orig;
      }

      // Resample
      $image_p = imagecreatetruecolor($width, $height);
      $image = imagecreatefromjpeg($fullpathToFile);
      imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

      // Output
      imagejpeg($image_p, null, 100);
      exit;
}
/**********************************************************\
 *  DOWNLOAD FILE                                         * 
 * This function will generate a download (or stream) of  *
 * the contents of the requested $fullPathToFile          *
\**********************************************************/
function downloadFile(){
    global $cfg, $fullpath, $path, $mode, $audioext, $config_inet_hash, $dirlist, $fullpathToFile, $action, $file;
    //clear out what might have been sent so far
    ob_clean();
    flush();

    //create the etag and check it for caching purposes
    $last_modified_time = filemtime($fullpathToFile); //create a variable for the last modified time
    $etag = md5($fullpathToFile.$last_modified_time); //create the etag using the file name + last modified time
    
    //send the last modified and etag headers (HTTP 1.1 browsers will use this
    header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
    header("Etag: $etag");

    //if the browser sent modified_since or none_match (etag) header, let's check against it
    if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
        header("HTTP/1.1 304 Not Modified");
        exit;
    }
    
    //get the file type
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    // if it's stream let's inline - if it's download let's attach
    if($action == "download"){
        header("Content-Disposition: attachment; filename=\"".$file."\"; "); //attachment to download, inline to view in browser
    }elseif($action == "stream"){
        header("Content-Disposition: inline; filename=\"".$file."\"; "); //attachment to download, inline to view in browser
    }
    
    //Set the content length and the transfer encoding
    header("Content-Length: ".filesize($fullpathToFile));
    header('Content-Transfer-Encoding: binary');			
    
    // We'll be outputting a ___ 
    $contenttype = returnMIMEtype($fullpathToFile);
    header("Content-Type: $contenttype");
    
    // The content of the file
    readfile($fullpathToFile);
    
    exit;
}
/**********************************************************\
 *  GENERATE ZIP FILE                                     * 
 * This function will generate a download (or stream) of  *
 * the contents of the requested $fullPathToFile          *
\**********************************************************/
function generateZipFile(){
    echo "Generating download zip file...<br />"; //this shouldn't even show up.
    echo "...for path: $fullpath<br />";
    
    $zipfile = new zipfile();

    //get the list of files in the logs directory
    if ($handle = opendir($fullpath)) {
        while (false !== ($zfile = readdir($handle))) {
            if ($zfile != "." && $zfile != ".." & $file != "cron") {
                if(!is_dir($fullpath."/".$zfile)){                    
                    //echo "Adding file ".$fullpath."/".$zfile."<br />";
                    //echo "Contents of file: <textarea>".file_get_contents($fullpath."/".$zfile)."</textarea>";
                    $zipfile->add_file(file_get_contents($fullpath."/".$zfile),$zfile);
                    //echo "Ok, the file was added<br />";
                }
            }
        }
        closedir($handle);
    }
    //echo "We got past the directory";
    
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-disposition: attachment; filename=FolderZip.zip");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    //header('Content-Length: ' . filesize($zipfile));
    ob_clean();
    flush();
    
    //echo "Now we cleaned and flushed everything...";
    
    echo $zipfile->file();
    exit;
}
/********************************************\
 *  Improved Version of imagecopyresampled  *
\********************************************/
function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {
  // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.
  // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled".
  // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.
  // Author: Tim Eckel - Date: 09/07/07 - Version: 1.1 - Project: FreeRingers.net - Freely distributable - These comments must remain.
  //
  // Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5. Must be greater than zero.
  // Between 0 and 1 = Fast, but mosaic results, closer to 0 increases the mosaic effect.
  // 1 = Up to 350 times faster. Poor results, looks very similar to imagecopyresized.
  // 2 = Up to 95 times faster.  Images appear a little sharp, some prefer this over a quality of 3.
  // 3 = Up to 60 times faster.  Will give high quality smooth results very close to imagecopyresampled, just faster.
  // 4 = Up to 25 times faster.  Almost identical to imagecopyresampled for most images.
  // 5 = No speedup. Just uses imagecopyresampled, no advantage over imagecopyresampled.

  if (empty($src_image) || empty($dst_image) || $quality <= 0) { return false; }
  if ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) {
    $temp = imagecreatetruecolor ($dst_w * $quality + 1, $dst_h * $quality + 1);
    imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h);
    imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality);
    imagedestroy ($temp);
  } else imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
  return true;
}

/******************************************************************\
 *        Find thumbnail function                                 *
 * ----------------------------------------                       *
 * Checks to see if a file exists based on a path (and optionally)*
 * a filename.                                                    *
 *                                                                *
 * Returns the filename if it already exists.                     *
 * Returns false if the file does not exists.                     *
 *                                                                *
 * If the thumbnail folder doesn't exist, the app will try to     *
 * create the directory                                           *
 *                                                                *
 * Returns "fail" if the directory could not be created           *
\******************************************************************/
function findthumbnail($fullpath, $filename){
    //if the path is set, but the file isnt
      if(isset($fullpath) && !isset($filename)){
          //split out the folder from the path
          preg_match('/([^\.]+)\/([^\/]+\.([^\/]+))$/', $fullpath, $matches);
          $fullpath = $matches[1];
          $filename = $matches[2];
          $ext = $matches[3];
      }

    //different methods of finding the thumbnails -- we'll start with one for now.
    //check to see if a .thumbs folder exists
    if(file_exists($fullpath."/.thumbs")){
        //echo "The thumbs folder exists <br />";
        if(file_exists($fullpath."/.thumbs/".$filename)){
            //echo "A thumbnail for the file exists<br />";
            return $filename;
        }
        else{
            return false;
        }
    }
    else{
        echo "<div class='infomessage'>The thumbnail folder doesn't exist - let's make it at: ".$fullpath."/.thumbs</div>";
        if(mkdir($fullpath."/.thumbs")){
            echo "<div class='infomessage'>Directory successfully created.</div>";
        }
        else {
            echo "<div class='warningmessage'>Could not create the directory. Check the permissions on the parent folder to make sure NewzBook has the appropriate access. [".substr(sprintf('%o', fileperms($fullpath)), -4)."]</div>";
            return "fail";
        }
        return false;
    }
}
/******************************************************************\
 *        Create Thumbnail function                               *
 * ----------------------------------------                       *
 * The create thumbnail function first calls the findthumbnail    *
 * function to check if the file already exists. Based on the     *
 * output of the findthumbnail function, the create thumbnail     *
 * function will either return the current thumbnail filename or  *
 * attempt to create the thumbnail.                               *
 *                                                                *
 * Returns:                                                       *
 * -the filename if the thumbnail exists or is successfully       *
 *  created.                                                      *
 * -"fail" if the directory could not be created                  *
 * -false if the thumbnail could not be created                   * 
\******************************************************************/
function createthumbnail($fullpath, $filename){
    //if the path contains our special thumbs directory, let's kill the function
    if(strpos($fullpath,".thumbs") != false){
        return "thumbdir";
    }
    //let's make sure the thumbnail doesn't exist first. If it exists, no need to continue, let's stop and return that filename
    $thumbnail = findthumbnail($fullpath, $filename);
    if($thumbnail != false){
        return $thumbnail;
    }
    //if we got this far, let's continue with the function
    //if the path is set, but the file isnt
    if(isset($fullpath) && !isset($filename)){
        //split out the folder from the path
        preg_match('/([^\.]+)\/([^\/]+\.([^\/]+))$/', $fullpath, $matches);
        $path = $matches[1];
        $filename = $matches[2];
        $ext = $matches[3];
        $fullpath = $path."/".$filename;
        $thumbnail = $path."/.thumbs/".$filename;
    }

    //create the thumbnail and save it to disk
    //ob_clean(); //clear what has been output so far
    //flush();
    // Set a maximum height and width
    $width = 100;
    $height = 100;

    // Content type
    //header('Content-type: image/jpeg');

    // Get new dimensions
    list($width_orig, $height_orig) = getimagesize($fullpath);

    $ratio_orig = $width_orig/$height_orig;

    if ($width/$height > $ratio_orig) {
       $width = $height*$ratio_orig;
    } else {
       $height = $width/$ratio_orig;
    }

    // Resample
    $image_p = imagecreatetruecolor($width, $height);
    $image = imagecreatefromjpeg($fullpath);
    fastimagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    // Output
    if(imagejpeg($image_p, $thumbnail, 100)){
        //echo "<div class='infomessage'>Successfully created the thumbnail at: $thumbnail</div>";
    }
    else{
        echo "<div class='warningmessage'>Could not create the file</div>";
        return false;
    }
    //then return the RELATIVE location of the thumbnail
    return $filename;
}

/******************************************************************\
 *        Mime Types                                              *
 * ----------------------------------------                       *
 * The mime_content_type() function was causing me a lot of head- *
 * ache so I am using this basic function found in the comments   *
 * the PHP.net site for other content-types.                      *
 *                                                                *
 * If the mime_content_type function doesn't exist, this function *
 * will return the basic mime types as I've defined them below.   * 
\******************************************************************/

function returnMIMEType($filename)
    {
        preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);

        switch(strtolower($fileSuffix[1]))
        {
            case "js" :
                return "application/x-javascript";

            case "json" :
                return "application/json";

            case "jpg" :
            case "jpeg" :
            case "jpe" :
                return "image/jpg";

            case "png" :
            case "gif" :
            case "bmp" :
            case "tiff" :
                return "image/".strtolower($fileSuffix[1]);

            case "css" :
                return "text/css";

            case "xml" :
                return "application/xml";

            case "doc" :
            case "docx" :
                return "application/msword";

            case "xls" :
            case "xlt" :
            case "xlm" :
            case "xld" :
            case "xla" :
            case "xlc" :
            case "xlw" :
            case "xll" :
                return "application/vnd.ms-excel";

            case "ppt" :
            case "pps" :
                return "application/vnd.ms-powerpoint";

            case "rtf" :
                return "application/rtf";

            case "pdf" :
                return "application/pdf";

            case "html" :
            case "htm" :
            case "php" :
                return "text/html";

            case "txt" :
                return "text/plain";

            case "mpeg" :
            case "mpg" :
            case "mpe" :
                return "video/mpeg";

            case "mp3" :
                return "audio/mpeg3";

            case "wav" :
                return "audio/wav";

            case "aiff" :
            case "aif" :
                return "audio/aiff";

            case "avi" :
                return "video/msvideo";

            case "wmv" :
                return "video/x-ms-wmv";

            case "mov" :
                return "video/quicktime";

            case "zip" :
                return "application/zip";

            case "tar" :
                return "application/x-tar";

            case "swf" :
                return "application/x-shockwave-flash";

            default :
            if(function_exists("mime_content_type"))
            {
                $fileSuffix = mime_content_type($filename);
            }

            return "unknown/" . trim($fileSuffix[0], ".");
        }
    }
//}
/*******************************************************************\
 *  NOW PLAYING                                                    *
 * ----------------------------------------                        *
 * This function checks to see if anything is playing on the PCH.  *
 * If something is playing, the function will output an HTML div   *
 * with the currently playing file                                 *
\*******************************************************************/
function nowPlaying(){
    //figure out what the currently playing song is (via processes)
    exec("ps -ww",$output); 
    $coolcommand = "ps | grep 'mono -audio' | sed 's/\(.* mono -audio -bgimg -single \)\(.*\)\(-dram 1\)/\2/'";
    //echo "<pre>$output</pre><br />";
    
    
    //process the results
    foreach($output as $item){
        //check for an audio match
        preg_match("/[^\/]+file\:\/\/(.+)\-dram 1/",$item,$matches);
        //check for a video match
        
        //print_r($matches);
        if(isset($matches[1])){
            $curritem = $matches[1];
        }
    }
    
    if($status == 0 && $curritem != ""){
        echo "<div class='nowplaying'>";
            echo "<strong>Now Playing:</strong><br />$curritem";
            echo "<div class='toggle_close'><a href='#' class='nowplayingtoggle'><img src='images/cross.png'/></a></div>";
        echo "</div>";
        return true;
    }
    else{
        return false;
    }
}
/*******************************************************************\
 *  SIDE PLAYLIST                                                  *
 * ----------------------------------------                        *
 * This function generates the HTML necessary to show the side     *
 * playlist (from the session variable playlist)                   *
\*******************************************************************/
function sidePlaylist($fullpath, $remoteplayenabled){
    if(isset($_SESSION['playlist'])){
        //if remote play is enabled leave the playlist in it's normal position
        if($remoteplayenabled){
            echo "<div class='sideplaylist'>";
        }
        else{
            //otherwise move it further up on the screen
            echo "<div class='sideplaylist aligntophigh'>";
        }
        //display a play all button
        echo "<strong>Playlist</strong>";
        if($remoteplayenabled){
            echo "<a href='?path=".urlencode($fullpath)."&action=remoteplay&mode=playlist'><img src='images/control_play.png'/>Play on PCH</a> | ";
        }
        echo "<a href='?path=".urlencode($fullpath)."&action=generateplaylist&mode=playlist'><img src='images/music.png'/>Generate Playlist</a><br /><br />";
        //loop through the playlist session variable (array) and output the current playlist
        foreach($_SESSION['playlist'] as $key => $item){
            echo "<form action='?path=".urlencode($fullpath)."' method='post' style='display:inline;vertical-align:top;'><input type='hidden' name='removefromqueue' value='".$key."'><input type='image' src='images/cross.png' value='Submit' alt='Submit'></form>".($key+1)." . ".htmlentities($item, ENT_QUOTES)."<br />";
        }
        echo "<form action='?path=".urlencode($fullpath)."' method='post' style='display:inline;vertical-align:top;'><input type='hidden' name='removefromqueue' value='everything'><input type='submit' value='Clear Playlist' alt='Submit'></form>";
        echo "<div class='toggle_close'><a href='#' class='sideplaylisttoggle'><img src='images/cross.png'/></a></div>";
        echo "</div>";
    }
}  
?>